package com.twang.stock.service.jinyan;

import com.alibaba.fastjson.JSONObject;
import com.twang.stock.entity.CompanyCodeInfo;
import com.twang.stock.entity.StockInfo;
import com.twang.stock.mapper.CompanyCodeInfoMapper;
import com.twang.stock.mapper.StockInfoMapper;
import com.twang.stock.threadPool.AsycTaskExecutorConfig;
import com.twang.stock.utils.clawer.HttpHelper;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.apache.http.client.config.CookieSpecs;
import org.apache.http.client.config.RequestConfig;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import org.jsoup.select.Elements;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.math.BigDecimal;
import java.util.Date;
import java.util.List;
@Service
@Slf4j
public class UpdateAndFixDataService {

    private static final String USER_AGENT = "Mozilla/5.0 (Linux; Android 5.0; SM-G900P Build/LRX21T) "
            + "AppleWebKit/537.36 (KHTML, like Gecko) Chrome/56.0.2924.87 Mobile Safari/537.36";
    private static final String COOKIE = "_gat=1; nsfw-click-load=off; gif-click-load=on;"
            + " _ga=GA1.2.1861846600.1423061484";
    @Resource
    private CompanyCodeInfoMapper companyCodeInfoMapper;

    @Autowired
    private CommonService commonService;
    @Resource
    private StockInfoMapper stockInfoMapper;
    @Autowired
    private CompanyCodeInfoService companyCodeInfoService;

    @Autowired
    private AsycTaskExecutorConfig asycTaskExecutorConfig;

    public void excute(String year,String season) {
//        Example example=new Example(CompanyCodeInfo.class);
//        example.createCriteria().andIsNull("companyShort");
//        List<CompanyCodeInfo> stockList=companyCodeInfoMapper.selectByExample(example);
        List<CompanyCodeInfo> stockList= companyCodeInfoMapper.selectAll();
        log.info(" 更新历史数据  start size={}",stockList.size());
        stockList.forEach(item->{
            asycTaskExecutorConfig.taskQueueExecutor().execute(() -> {
                try {
                    log.info(" 更新历史数据  start code={}",item);
                    updateHistortData(item.getCompanyCode(),year, season);
                    log.info(" 更新历史数据  end code={}",item);
                } catch (Exception e) {
                    log.info(" 更新主力资金异常 e={}",e);
                }
            });
        });
    }


    public void updateHistortData(String stock,String year,String season) throws Exception {
        if (StringUtils.isEmpty(stock) || StringUtils.isEmpty(year) || StringUtils.isEmpty(season)) {
            throw new Exception("代码不能为空！");
        }
        // HttpClient 超时配置
        RequestConfig globalConfig = RequestConfig.custom().setCookieSpec(CookieSpecs.STANDARD)
                .setConnectionRequestTimeout(6000).setConnectTimeout(6000).build();
        CloseableHttpClient httpClient = HttpClients.custom().setDefaultRequestConfig(globalConfig).build();
        StringBuffer url = new StringBuffer("").append("http://quotes.money.163.com/trade/lsjysj_").append(stock.substring(2, 8)).append(".html?year=").append(year).append("&season=").append(season);
        String urlToReq = "";
        try {
            // 发送请求，并执行
            String htmlForStock = HttpHelper.getHtmlStrByUrl(url.toString(), httpClient, COOKIE, USER_AGENT);
            // 网页内容解析
            log.info("该网页存在,正在解析:{}", htmlForStock);
            Document doc = Jsoup.parse(htmlForStock);
            // 获取table表的行集合元素
            Elements trs = doc.select("table[class=table_bg001 border_box limit_sale]").select("tr");
            //   doc
            for (int j = 1; j < trs.size(); j++) {
                Elements tds = trs.get(j).select("td");
                StockInfo info = new StockInfo();
                info.setCode(stock);
                try {
                    info.setName(companyCodeInfoService.getInfoByStockName(stock).getShortName());
                    //日期
                    String date = tds.get(0).html().replace("-", "");
                    //收盘价
                    info.setPrice(new BigDecimal(tds.get(4).html().replace(",", "")));
                    //成交量(手)
                    info.setVolMay1(Integer.valueOf(tds.get(7).html().replace(",", "")));
                    //最高价
                    info.setPriceMax(new BigDecimal(tds.get(2).html().replace(",", "")));
                    //最低价
                    info.setPriceMin(new BigDecimal(tds.get(3).html().replace(",", "")));
                    info.setVolMay1Avg(info.getVolMay1() / 240);
                    info.setCreateTime(new Date());
                    info.setDate(date);
                    insertOrUpdate(info);
                } catch (Exception e) {
                    log.error("erro={}", e);
                }
            }

        } catch (Exception e) {
            log.error("erro={}", e);
        }

    }
    public int insertOrUpdate(StockInfo stockInfo) {
        StockInfo param = new StockInfo();
        param.setCode(stockInfo.getCode());
        param.setDate(stockInfo.getDate());
        StockInfo history = queryByDto(param);
        if (null == history) {
            return stockInfoMapper.insert(stockInfo);
        }else{
            history.setPrice(stockInfo.getPrice());
            history.setVolMay1(stockInfo.getVolMay1());
            history.setPriceMax(stockInfo.getPriceMax());
            history.setPriceMin(stockInfo.getPriceMin());
            history.setVolMay1Avg(stockInfo.getVolMay1Avg());
            history.setCreateTime(new Date());
            stockInfoMapper.updateByPrimaryKey(history);
        }
        return 0;
    }

    public StockInfo queryByDto(StockInfo param) {
        List<StockInfo> list = stockInfoMapper.select(param);
        if (list.size() > 0) {
            log.info(" 历史记录存在  size={} list--->{}",list.size(),JSONObject.toJSONString(list));
            return list.get(0);
        } else {
            return null;
        }
    }

}
